package com.ecarx.library_base.usb;


import android.content.Intent;
import android.content.IntentFilter;

import com.ecarx.library_base.BaseApplication;
import com.ecarx.library_base.usb.brodcast.USBReceiver;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UDiskManager implements USBReceiver.UsbChangeCallback {

    private USBReceiver mUsbReceiver;

    private final List<USBReceiver.UsbChangeCallback> mUdiskChangeListenerList = Collections.synchronizedList(new ArrayList<>());

    private UDiskManager() {
    }

    private static class Inner {
        private static final UDiskManager sUDiskManager = new UDiskManager();
    }

    public static UDiskManager getInstance() {
        return UDiskManager.Inner.sUDiskManager;
    }

    @Override
    public void onUsbDeviceChanged(boolean isAdd, List<UDiskDevice> uDiskDeviceList) {
        for (USBReceiver.UsbChangeCallback uDiskChangeListener : mUdiskChangeListenerList) {
            uDiskChangeListener.onUsbDeviceChanged(isAdd, uDiskDeviceList);
        }
    }

    public void addUDiskChangeListener(USBReceiver.UsbChangeCallback uDiskChangeListener) {
        if (!mUdiskChangeListenerList.contains(uDiskChangeListener)) {
            mUdiskChangeListenerList.add(uDiskChangeListener);
        }
        if (mUsbReceiver == null) {
            registerReceiver();
        }
    }

    public void removeUDiskChangeListener(USBReceiver.UsbChangeCallback uDiskChangeListener) {
        mUdiskChangeListenerList.remove(uDiskChangeListener);
        if (mUdiskChangeListenerList.isEmpty()) {
            unRegisterReceiver();
        }
    }

    public List<UDiskDevice> getAllUDiskDevice() {
        return UDiskUtil.getUDiskDeviceList();
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
        filter.setPriority(1000);
        filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
        filter.addDataScheme("file");
        mUsbReceiver = new USBReceiver(this);
        BaseApplication.getInstance().registerReceiver(mUsbReceiver, filter);
    }

    private void unRegisterReceiver() {
        if (mUsbReceiver != null) {
            BaseApplication.getInstance().unregisterReceiver(mUsbReceiver);
            mUsbReceiver = null;
        }
    }

}
